package com.shujia.day17.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(7777);
        try {
            while (true){
                Socket socket = serverSocket.accept();  // 阻塞
                OutputStream outputStream = socket.getOutputStream();
                InputStream inputStream = socket.getInputStream();

                new ServerInput("服务端输入流：", inputStream).start();
                new ServerOutput("服务端输出流：", outputStream).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            serverSocket.close();
        }
    }

    static class ServerInput extends Thread {
        InputStream inputStream;
        BufferedReader bufferedReader;

        public ServerInput(String name, InputStream inputStream) {
            super(name);
            this.inputStream = inputStream;
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        }

        @Override
        public void run() {
            String line = "";
            try {
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(this.getName() + "接收:" + line);
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }

    static class ServerOutput extends Thread {
        OutputStream outputStream;
        Scanner scanner;

        public ServerOutput(String name, OutputStream outputStream) {
            super(name);
            this.outputStream = outputStream;
            scanner = new Scanner(System.in);
        }

        @Override
        public void run() {
            System.out.println("输出流线程开始工作...");
            try {
                while (true) {

                    System.out.println("请输入您要发送的信息:");
                    if (scanner.hasNext()) {
                        String message = scanner.next();
                        // 将输入的信息进行输出
                        outputStream.write((message + "\n").getBytes());
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }
}
